package cn.hpclub.server.controller.admin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.bean.SystemConfig;
import cn.hpclub.server.model.Notice;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.SystemConfigUtil;

public class NoticeController extends BaseAdminController<Notice>{

    private static Logger       logger    = LoggerFactory.getLogger(NoticeController.class);
    private static final String DIR_HTML5 = "/file/html5/notice/";
    private static final String URL_HTML5 = SystemConfig.UPLOAD_FILE_DIR + "html5/notice/";

    /**
     * @Title: list
     * @Description: 列表
     */
    public void list(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();

        String select = " select n.*, (select user_name from sys_user where is_deleted = 0 and id = n.created_by) as creator ";
        findByPageForSearch(select, new Notice().getSqlExceptSelect(searchInfo));

        setAttrs(searchInfo);
        render("/admin/notice_list.tpl");
    }

    /**
     * @Title: add
     * @Description:获取新增页面
     */
    public void add(){
        setAttr("noticeID", -1);

        render("/admin/notice_input.tpl");
    }

    /**
     * @Title: edit
     * @Description:编辑
     */
    public void edit(){
        String id = getPara("id");

        Notice notice = Notice.dao.findById(id);

        setAttr("noticeID", notice.getInt("id"));
        setAttr("noticeType", notice.getInt("type"));
        setAttr("noticeEnabled", notice.getInt("enabled"));
        setAttr("isTop", notice.getInt("is_top"));
        setAttr("imageUrl", notice.getStr("image"));
        setAttr("shortDesc", notice.getStr("short_desc"));
        setAttr("noticeDetail", notice.getStr("description"));
        setAttr("publishTime", notice.getTimestamp("created_time"));
        setAttr("noticeTitle", notice.getStr("title"));
        setAttr("noticeSort", notice.getInt("sort"));
        setAttr("seoTitle", notice.getStr("seo_title"));
        setAttr("seoKeywords", notice.getStr("seo_keywords"));
        setAttr("seoDescription", notice.getStr("seo_description"));
        setAttr("orgID", notice.getInt("org_id"));

        render("/admin/notice_input.tpl");
    }

    /**
     * @Title: save
     * @Description:保存提交来自页面的数据
     */
    public void save(){
        int id = getParaToInt("noticeID");

        if(id == -1){
            addNotice();
        } else{
            editNotice();
        }

        redirect("/notice/list");
    }

    public void addNotice(){
        Notice notice = getModel(Notice.class);
        String noticeTitle = getPara("noticeTitle");
        String createdTime = getPara("publishTime");
        String image = getPara("imageUrl");
        String desc = getPara("noticeDetail");

        notice.set("type", getPara("noticeType"));
        notice.set("enabled", getPara("noticeEnabled"));
        notice.set("is_top", getPara("isTop"));
        notice.set("title", noticeTitle);
        notice.set("image", image);
        notice.set("short_desc", getPara("shortDesc"));
        notice.set("description", desc);
        notice.set("created_time", createdTime);
        notice.set("title", noticeTitle);
        notice.set("sort", getPara("noticeSort"));
        notice.set("seo_title", getPara("seoTitle"));
        notice.set("seo_keywords", getPara("seoKeywords"));
        notice.set("seo_description", getPara("seoDescription"));
        notice.set("org_id", InterfaceUtil.getOrgId());
        notice.set("created_by", InterfaceUtil.getAdminId());

        notice.save();
        int parimaryID = notice.getInt("id");

        saveHTML5(parimaryID, noticeTitle, createdTime, image, desc);
    }

    private void saveHTML5(int parimaryID, String noticeTitle, String createdTime, String image, String desc){
        // 产生HTML5页面
        String h5Str = getHTML5Contents(noticeTitle, createdTime, image, desc);
        // String realPath =
        // JFinal.me().getServletContext().getRealPath(DIR_HTML5);
        String realPath = SystemConfigUtil.getSystemConfig().getUploadDir() + DIR_HTML5;
        String fileName = parimaryID + ".html";
        logger.debug("realPath:" + realPath);
        logger.debug("fileName:" + fileName);
        boolean success = createHTML5File(realPath, fileName, h5Str);

        if(success){
            // update db
            Notice notice = new Notice();
            notice.set("id", parimaryID);
            notice.set("h5_url", URL_HTML5 + fileName);

            notice.update();
        }
    }

    public void editNotice(){
        Notice notice = getModel(Notice.class);
        int parimaryID = getParaToInt("noticeID");
        String noticeTitle = getPara("noticeTitle");
        String createdTime = getPara("publishTime");
        String image = getPara("imageUrl");
        String desc = getPara("noticeDetail");

        notice.set("id", parimaryID);
        notice.set("type", getPara("noticeType"));
        notice.set("enabled", getPara("noticeEnabled"));
        notice.set("is_top", getPara("isTop"));
        notice.set("title", noticeTitle);
        notice.set("image", image);
        notice.set("short_desc", getPara("shortDesc"));
        notice.set("description", desc);
        notice.set("created_time", createdTime);
        notice.set("title", noticeTitle);
        notice.set("sort", getPara("noticeSort"));
        notice.set("seo_title", getPara("seoTitle"));
        notice.set("seo_keywords", getPara("seoKeywords"));
        notice.set("seo_description", getPara("seoDescription"));
        notice.set("org_id", InterfaceUtil.getOrgId());
        notice.set("last_updated_by", InterfaceUtil.getAdminId());
        notice.set("last_updated_time", new Date());

        notice.update();

        saveHTML5(parimaryID, noticeTitle, createdTime, image, desc);
    }

    @Before(Tx.class)
    public void delete() throws SQLException{
        String[] ids = getParaValues("ids");
        if(ids == null || ids.length <= 0){
            ajaxJsonErrorMessage("删除失败，无选中项");
        }

        boolean deleted = deleteNoticeByIDs(ids);

        if(deleted){
            ajaxJsonSuccessMessage("删除成功！");
        } else{
            ajaxJsonErrorMessage("删除失败！");
            throw new SQLException("通知删除失败");
        }
    }

    private boolean deleteNoticeByIDs(String[] ids){
        boolean deleted = true;
        for(String id : ids){
            Notice notice = new Notice();
            notice.set("id", id);
            notice.set("is_deleted", 1);
            notice.set("last_updated_by", InterfaceUtil.getAdminId());
            notice.set("last_updated_time", new Date());
            if(!notice.update()){
                deleted = false;
                break;
            }
        }

        return deleted;
    }

    private String getHTML5Contents(String inTitle, String inTime, String inImage, String inDescription){
        // HTML5
        String docType = "<!DOCTYPE html>";
        String prefixHead = " <html xmlns='http://www.w3.org/1999/xhtml'> " + " <head> " + " <meta charset='utf-8' /> "
                + " <meta name='viewport' "
                + " content='height=device-height,width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no'/> "
                + " <meta content='telephone=no' name='format-detection' /> " + " <title> ";
        String style = " </title> <style> "
                + " *{padding:0;margin:0}p{display:block;-webkit-margin-before:1em;-webkit-margin-after:1em; "
                + " -webkit-margin-start:0px;-webkit-margin-end:0px}.main{min-width:280px;margin-left:16px; "
                + " margin-right:16px;font-family:'黑体'}.title{font-weight:bold; "
                + " margin-top:30px;margin-bottom:10px}.src{font-weight:bold;color:#aaaaaa}.text{line-height:25px; "
                + " text-align:justify}.preLoad{position:relative;display:block;margin:1em "
                + " auto;overflow:hidden;border:1px solid#dedada;background:#ede9e6}.preLoad "
                + " div.tip{position:absolute;z-index:11;bottom:5px;right:7px;color:#B7B7B7;font-style:italic;font-size:14px;text-shadow:1px "
                + " 1px 1px rgba(255,255,255,.8);-webkit-text-shadow:1px 1px 1px rgba(255,255,255,.8)}.preLoad "
                + " div.img{position:relative;z-index:12} " + " </style> </head> " + " <body> "
                + " <div id='content' class='main'> " + " <p class='title' align='left'> ";
        String prefixTime = "  </p> <span class='src'> ";
        String postfixTime = " </span> <p class='text'> <div class='preLoad' style='width:100%;'> "
                + " <div class='img'> " + " <img src= '";
        String postfixImageContent = "' style='width:100%;display:block;' /> " + " </div> " + " </div> " + " </p> ";
        String postfixHead = " </div>  <div class='clear'> " + " </div> " + " </body> " + " </html> ";

        StringBuffer contents = new StringBuffer();
        contents.append(docType);
        contents.append(prefixHead);
        // Title
        contents.append(inTitle);
        contents.append(style);
        // Title
        contents.append(inTitle);
        contents.append(prefixTime);
        // DateTime
        contents.append(inTime);
        contents.append(postfixTime);
        // image
        contents.append("../../../.." + inImage);
        contents.append(postfixImageContent);
        // description
        contents.append((inDescription == null) ? "" : inDescription);
        contents.append(postfixHead);

        // 字符串编码 UTF-8

        return contents.toString();
    }

    private boolean createHTML5File(String filePath, String fileName, String fileContents){
        File path = new File(filePath);
        if(!path.exists()){
            path.mkdirs();
        }

        byte bt[] = new byte[fileContents.length() + 1];
        try{
            bt = fileContents.getBytes("UTF-8");
            File file = new File(path, fileName);
            FileOutputStream out = new FileOutputStream(file);
            out.write(bt, 0, bt.length);
            out.close();

            return true;
        }
        catch(IOException e){
            e.printStackTrace();
        }

        return false;
    }
}
